<?php

namespace App\Http\Controllers\Site\Custom\Provider;

use App\B2BProject\Site\HelperControllerBuildTrait;
use App\B2BProject\Custom\Business\Brand;
use App\B2BProject\Custom\Business\GoodsCategory;
use App\B2BProject\Custom\Business\GoodsImage;
use App\B2BProject\Custom\Business\GoodsSpecification;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use App\B2BProject\Custom\Business\Goods;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class GoodsController extends Controller
{
    use HelperControllerBuildTrait;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $request->query->set('page', $request->query('page', $request->page));
            $pageSize = $request->query('pageSize', $request->pageSize);

            $goods = Goods::AvailableStore();

            if ($categoryId = $request->query('classify')) {
                $goods->where('category_id', $categoryId);
            }

            if ($state = $request->query('state')) {
                switch ($state) {
                    case 1:
                        $goods->where('grant_status', true);
                        break;
                    case 2:
                        $goods->where('grant_status', false);
                        break;
                    case 3:
                        $goods->where('display', true);
                        break;
                    case 4:
                        $goods->where('display', false);
                        break;
                    case 5:
                        $goods->where('recommend_status', true);
                        break;
                    case 6:
                        $goods->where('sell_status', false);
                        break;
                }
            }

            if ($name = $request->query('goodName')) {
                $goods->where('name', 'like', "%$name%");
            }

            $goods = $goods->orderBy('created_at', 'desc')->paginate($pageSize);

            $data = [];

            foreach ($goods as $good) {
                $data[] = [
                    'id'        => $good->id,
                    'name'      => $good->name,
                    'classify'  => $good->category->name,
                    'price'     => $good->original_price,
                    'stock'     => $good->stock,
                    'authority' => !$good->grant_status,
                    'stacking'  => $good->sell_status,
                    'recommend' => $good->recommend_status,
                    'lock'      => $good->sell_status,
                    'img'       => $good->cover(),
                    'edit_url'  => route('account.goods.edit', [$good->id]),
                ];
            }

            return response()->json([
                'data'           => $data,
                'pagingConfData' => [
                    'page'     => $goods->currentPage(),
                    'pageSize' => $request->query('pageSize'),
                    'total'    => $goods->total(),
                ],
            ]);
        }

        // 搜索栏分类列表
        $collection = Auth::user()->store->categories()->where('parent_id', 0)->get();

        $categories = [];

        foreach ($collection as $base) {
            $categories[] = [
                'code' => $base->id,
                'text' => $base->name
            ];

            foreach ($base->children as $child) {
                $categories[] = [
                    'code' => $child->id,
                    'text' => '- ' . $child->name
                ];
            }
        }

        return view('host/custom/provider/goods/index')->with('categories', $categories);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $goods_categories = GoodsCategory::where('parent_id', '=', 0)->where('store_id', 0)->get();
        $store            = Auth::user()->store;//获取店铺信息
        $store_categories = GoodsCategory::where('parent_id', '=', 0)->where('store_id', $store->id)->get();

        return view('host/custom/provider/goods/create')->with('goods_categories',
            $goods_categories)->with('store_categories', $store_categories);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Requests\GoodsPublishRequest $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Requests\GoodsPublishRequest $request)
    {
        $store = Auth::user()->store;//获取店铺信息

        try {
            \DB::transaction(function () use ($request, $store) {
                // 获取全局总分类
                $class = GoodsCategory::where('store_id', 0)->whereId($request->input('class_id'))->firstOrFail();

                // 获取店铺分类
                $category = $store->categories()->whereId($request->input('category_id'))->firstOrfail();

                // 获取品牌
                $brand = Brand::findOrFail($request->input('brand_id'));

                // 获取数据
                $data = $request->only([
                    'name',
                    'original_price',
                    'province_id',
                    'city_id',
                    'county_id',
                    'stock',
                    'minimum_order',
                    'cn',
                    'unit',
                    'display',
                    'sell_status',
                    'recommend_status',
                    'detail',
                ]);

                // 获取商品供采分销授权标记，默认为自由贸易商品
                $data['grant_status'] = $request->input('grant_status', 0);

                // 规格部分数据读取
                $data['spec_first_name']  = $request->input('spec_first_name', '');
                $data['spec_second_name'] = $request->input('spec_second_name', '');
                $data['spec_third_name']  = $request->input('spec_third_name', '');
                $data['spec_forth_name']  = $request->input('spec_forth_name', '');
                $data['spec_fifth_name']  = $request->input('spec_fifth_name', '');

                //创建商品对象
                $good = Goods::create($data);


                // 上传图片
                $files = $request->file('img');

                // 保存商品图片
                foreach ($files as $key => $file) {
                    if (is_null($file)) {
                        continue;
                    }

                    $file_name = Str::random(8) . '.' . $file->getClientOriginalExtension();
                    $target    = $file->move(base_path('public/data/upload/goods'), $file_name);
                    $imagePath = str_replace(base_path('public'), '', $target);

                    $goodsImage        = new GoodsImage();
                    $goodsImage->image = $imagePath;
                    $goodsImage->sort  = $key;
                    $goodsImage->save();
                    $good->goodsImage()->save($goodsImage);
                }

                // 所需规格数据
                $goodsSpec = $request->input('spec_first', []);
                foreach ($goodsSpec as $key => $value) {
                    $goodSpecInstance                 = new GoodsSpecification();
                    $goodSpecInstance->spec_first     = $request->spec_first[$key];
                    $goodSpecInstance->spec_second    = $request->spec_second[$key];
                    $goodSpecInstance->spec_third     = $request->spec_third[$key];
                    $goodSpecInstance->spec_forth     = $request->spec_forth[$key];
                    $goodSpecInstance->spec_fifth     = $request->spec_fifth[$key];
                    $goodSpecInstance->original_price = $request->spec_original_price[$key];
                    $goodSpecInstance->stock          = $request->spec_stock[$key];
                    $goodSpecInstance->cn             = $request->spec_cn[$key];

                    $goodSpecInstance->save();

                    $good->goodsSpecification()->save($goodSpecInstance);
                }

                // 关联数据保存
                $class->allGoods()->save($good);
                $category->goods()->save($good);
                $brand->goods()->save($good);

                $store->goods()->save($good); // 保存数据
            });
        } catch (ModelNotFoundException $e) {
            throw $e;
        }

        return redirect()->route('account.goods.index');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $goods_categories = GoodsCategory::where('parent_id', '=', 0)->where('store_id', 0)->get();
        $store            = Auth::user()->store;//获取店铺信息
        $store_categories = GoodsCategory::where('parent_id', '=', 0)->where('store_id', $store->id)->get();

        $goods      = Goods::findOrFail($id);
        $goodsSpecs = call_user_func_array(function ($specs) {
            $ids = [];
            foreach ($specs as $spec) {
                $ids[] = $spec->id;
            }

            return implode(',', $ids);
        }, [$goods->goodsSpecification]);

        return view('host/custom/provider/goods/edit')->with('goods', $goods)->with('goods_categories',
            $goods_categories)->with('store_categories', $store_categories)->with('goods_specs', $goodsSpecs);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Requests\GoodsPublishRequest $request
     * @param  int                          $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Requests\GoodsPublishRequest $request, $id)
    {

        $store = Auth::user()->store;//获取店铺信息
        try {
            \DB::transaction(function () use ($request, $store, $id) {
                $class    = GoodsCategory::where('store_id', 0)->whereId($request->input('class_id'))->firstOrFail();
                $category = $store->categories()->whereId($request->input('category_id'))->firstOrfail();
                $brand    = Brand::whereId($request->input('brand_id'))->firstOrFail();

                $data = $request->only([
                    'name',
                    'brand_id',
                    'original_price',
                    'province_id',
                    'city_id',
                    'county_id',
                    'stock',
                    'minimum_order',
                    'cn',
                    'unit',
                    'display',
                    'sell_status',
                    'recommend_status',
                    'detail',
                ]);// 只取这些数据，获取数据2步:

                $good = Goods::findOrFail($id); // 3步:查询数据是否存在并实例化模型类

                // 获取商品供采分销授权标记，默认为自由贸易商品
                $data['grant_status'] = $request->input('grant_status', 0);

                // 规格部分数据读取
                $data['spec_first_name']  = $request->input('spec_first_name', '');
                $data['spec_second_name'] = $request->input('spec_second_name', '');
                $data['spec_third_name']  = $request->input('spec_third_name', '');
                $data['spec_forth_name']  = $request->input('spec_forth_name', '');
                $data['spec_fifth_name']  = $request->input('spec_fifth_name', '');

                // 判断是否上传了新的图片
                $files = $request->file('img');

                // 保存商品图片
                foreach ($files as $key => $file) {
                    if (is_null($file)) {
                        continue;
                    }

                    $file_name = Str::random(8) . '.' . $file->getClientOriginalExtension();
                    $target    = $file->move(base_path('public/data/upload/goods'), $file_name);
                    $imagePath = str_replace(base_path('public'), '', $target);

                    // TODO 目前只允许一张图，因此在这里仅仅做了替换
                    $old = $good->goodsImage()->first();
                    $old->image = $imagePath;
                    $old->save();
                }

                // 所需规格数据
                $goodsSpec = $request->input('spec_first', []);
                foreach ($goodsSpec as $key => $value) {
                    if (empty($specId = $request->input(sprintf("spec_id.%d", $key)))) {
                        $goodSpecInstance = new GoodsSpecification();
                    } else {
                        $goodSpecInstance = GoodsSpecification::findOrFail($specId);
                    }

                    $goodSpecInstance->spec_first     = $request->spec_first[$key];
                    $goodSpecInstance->spec_second    = $request->spec_second[$key];
                    $goodSpecInstance->spec_third     = $request->spec_third[$key];
                    $goodSpecInstance->spec_forth     = $request->spec_forth[$key];
                    $goodSpecInstance->spec_fifth     = $request->spec_fifth[$key];
                    $goodSpecInstance->original_price = $request->spec_original_price[$key];
                    $goodSpecInstance->stock          = $request->spec_stock[$key];
                    $goodSpecInstance->cn             = $request->spec_cn[$key];

                    $goodSpecInstance->save();

                    $good->goodsSpecification()->save($goodSpecInstance);
                }

                $good->update($data);   // 4步:修改数据库数据

                $class->allGoods()->save($good);
                $category->goods()->save($good);
                $brand->goods()->save($good);
                $store->goods()->save($good); // 保存数据
            });
        } catch (ModelNotFoundException $e) {
            throw $e;
        }

        return redirect()->route('account.goods.index');
    }

    /**
     * 删除指定商品
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        try {
            $ids = $request->id;

            if (is_array($ids)) {
                // 由于是商品的删除，因此细化操作
                foreach ($ids as $id) {
                    $good = Goods::findOrFail($id);
                    // 清理购物车前为防止被进行下一步所做的操作
                    $good->sell_status = false; // 禁售
                    $good->save();

                    $good->delete();
                }
            } else {
                $good = Goods::findOrFail($ids);
                // 清理购物车前为防止被进行下一步所做的操作
                $good->sell_status = false; // 禁售
                $good->save();

                $good->delete();
            }
        } catch (ModelNotFoundException $e) {
            if ($request->ajax()) {
                return response()->json(['data' => '未找到指定的商品'], 404);
            }

            abort(404);
        }

        return $this->index($request);
    }
}
